#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "../MainProject/loggermanager.h"

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
    , dataMonitorPage(new DataMonitor(this))
    , circleChartPage(new CircleChartPage(this))
    , db(SQLiteDatabase::getInstance())
{
    ui->setupUi(this);

    QFile dataMonitorFile(":/qss/DataMonitorQSS.qss");
    if (dataMonitorFile.open(QFile::ReadOnly)) {
        QString styleSheet = QLatin1String(dataMonitorFile.readAll());
        this->setStyleSheet(styleSheet);
    }else{
        qDebug() <<"UserManger QSS打开失败";
    }

    Logger().init();
    // 从数据库中读取设备 ID 并填充到 QComboBox
    QJsonArray devices = db->read("devices");
    for (const QJsonValue &value : devices) {
        QJsonObject obj = value.toObject();
        int deviceId = obj["device_id"].toString().toInt();
        QString deviceName = obj["name"].toString();
        qDebug() << "Adding device to combo box:" << deviceName << "with ID:" << deviceId;
        ui->selectSerialComboBox->addItem(deviceName, QVariant(deviceId));
        //addItem(deviceName, QVariant(deviceId)) 方法将设备名称作为显示文本，设备ID作为关联数据添加到组合框中。
    }

    // 连接 QComboBox 的信号到槽函数
    //QOverload 是一个模板结构，它被用来解决 Qt 信号和槽机制中的函数重载问题。
    //在 Qt 中，QOverload 帮助我们在使用 QObject::connect 函数时明确指定哪一个重载函数应该被连接。
    connect(ui->selectSerialComboBox, QOverload<int>::of(&QComboBox::currentIndexChanged), this, &MainWindow::onDeviceSelected);

    // 将页面添加到 QStackedWidget
    ui->stackedWidget->addWidget(dataMonitorPage);
    ui->stackedWidget->addWidget(circleChartPage);

    // 连接按钮信号到槽函数
    connect(ui->showDataMonitorButton, &QPushButton::clicked, this, &MainWindow::showDataMonitorPage);
    connect(ui->showCircleChartButton, &QPushButton::clicked, this, &MainWindow::showCircleChartPage);

    // 连接 DataMonitor 的数据更新信号到 CircleChartPage 的数据更新槽
    connect(dataMonitorPage, &DataMonitor::temperatureDataUpdated, circleChartPage, &CircleChartPage::addTemperatureData);
    connect(dataMonitorPage, &DataMonitor::humidityDataUpdated, circleChartPage, &CircleChartPage::addHumidityData);
    connect(dataMonitorPage, &DataMonitor::lightDataUpdated, circleChartPage, &CircleChartPage::addLightData);

    // 默认显示实时数据页面
    ui->stackedWidget->setCurrentWidget(dataMonitorPage);

    onDeviceSelected(ui->selectSerialComboBox->currentIndex());
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::showDataMonitorPage()
{
    ui->stackedWidget->setCurrentWidget(dataMonitorPage);
}

void MainWindow::showCircleChartPage()
{
    ui->stackedWidget->setCurrentWidget(circleChartPage);
}

void MainWindow::onDeviceSelected(int index)
{
    int deviceId = ui->selectSerialComboBox->itemData(index).toInt();
    qDebug() << "Selected device ID:" << deviceId;
    dataMonitorPage->setCurrentDevice(deviceId);
}
